﻿using PSI.Helper;
using PSI.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace PSI.Services {
    public class MainMenuService : PSIBaseService {
        public List<MenuItem> GetAllMenuItems(User user) {
            var sql = "select menu_id, menu_caption, show_order, parent_id, fid from psi_main_menu";

            var result = new List<MenuItem>();

            Query(sql, reader => {
                var mi = new MenuItem {
                    Id = reader.GetString(0),
                    Caption = reader.GetString(1),
                    ShowOrder = reader.GetInt32(2),
                    ParentId = reader.GetString(3),
                    FId = reader.GetString(4)
                };

                result.Add(mi);
            });

            return result;
        }

        private List<string> GetFidByPermision(string userId) {
            var result = new List<string>() { 
                "-9996", "-9997", "-9998", "-9999"
            };


            var sql = @"select distinct p.fid
                        from psi_user_role ur, psi_role_permission rp, psi_permission p
                        where ur.user_id = @userId and ur.role_id = rp.role_id 
                            and rp.permission_id = p.permission_id";
            var p = CreateDbParameters();
            p.AddWithValue("userId", userId);
            Query(sql, p, reader => {
                result.Add(reader.GetString(0));
            });

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ignorePermission">是否忽略权限。true的时候不考虑当前用户的权限，显示所有的菜单</param>
        /// <returns></returns>
        public MenuItem BuildMenuItemTree(bool ignorePermission) {
            var user = UserService.GetLoginUser();
            var data = GetAllMenuItems(user);
            var permissionFidList = GetFidByPermision(user.Id);

            var root = new MenuItem();

            var menu1 = from item in data
                        where item.ParentId == string.Empty
                        orderby item.ShowOrder
                        select item;

            foreach (var m1 in menu1) {
                var mvLevel1 = new MenuItem {
                    Id = m1.Id,
                    Caption = m1.Caption,
                    FId = m1.FId,
                    ShowOrder = m1.ShowOrder
                };


                // 二级菜单
                var menu2 = from item in data
                            where item.ParentId == m1.Id
                            orderby item.ShowOrder
                            select item;
                foreach (var m2 in menu2) {
                    var mvLevel2 = new MenuItem {
                        Id = m2.Id,
                        Caption = m2.Caption,
                        FId = m2.FId,
                        ShowOrder = m2.ShowOrder
                    };

                    // 三级菜单
                    var menu3 = from item in data
                                where item.ParentId == m2.Id
                                orderby item.ShowOrder
                                select item;

                    foreach (var m3 in menu3) {
                        if (ignorePermission) {
                            mvLevel2.Children.Add(new MenuItem {
                                Id = m3.Id,
                                Caption = m3.Caption,
                                FId = m3.FId,
                                ShowOrder = m3.ShowOrder
                            });
                        } else if (permissionFidList.IndexOf(m3.FId) != -1) {
                            mvLevel2.Children.Add(new MenuItem {
                                Id = m3.Id,
                                Caption = m3.Caption,
                                FId = m3.FId,
                                ShowOrder = m3.ShowOrder
                            });
                        }
                    }

                    if (ignorePermission) {
                        mvLevel1.Children.Add(mvLevel2);
                    } else if (mvLevel2.FId == string.Empty && mvLevel2.Children.Count > 0) {
                        mvLevel1.Children.Add(mvLevel2);
                    } else if (permissionFidList.IndexOf(mvLevel2.FId) != -1) {
                        mvLevel1.Children.Add(mvLevel2);
                    }
                }
                if (ignorePermission) {
                    root.Children.Add(mvLevel1);
                } else if (mvLevel1.Children.Count > 0) {
                    // 只有具有子菜单的时候，才把其加入到父节点
                    root.Children.Add(mvLevel1);
                }
            }

            return root;
        }


        public List<FId> GetFid() {
            var result = new List<FId>();

            var sql = "select id, name from psi_fid order by id";
            Query(sql, reader => {
                var fid = new FId {
                    Id = reader.GetString(0),
                    Name = reader.GetString(1)
                };

                result.Add(fid);
            });

            return result;
        }

        public string GetFidCaption(string fid) {
            var sql = "select name from psi_fid where id = @id";

            var p = CreateDbParameters();
            p.AddWithValue("id", fid);

            return QueryObject<string>(sql, p, reader => { return reader.GetString(0); });
        }

        public MenuItem Get(string id) {
            var sql = "select menu_caption, show_order, parent_id, fid from psi_main_menu where menu_id = @menuId";
            var db = DBHelper.AdoTemplate;
            var p = db.CreateDbParameters();
            p.AddWithValue("menuId", id);

            var result = db.QueryObject<MenuItem>(sql, reader => {
                return new MenuItem {
                    Caption = reader.GetString(0),
                    ShowOrder = reader.GetInt32(1),
                    ParentId = reader.GetString(2),
                    FId = reader.GetString(3)
                };
            }, p);

            if (!string.IsNullOrEmpty(result.ParentId)) {
                sql = "select menu_caption from psi_main_menu where menu_id = @menuId";
                p = db.CreateDbParameters();
                p.AddWithValue("menuId", result.ParentId);
                db.Query(sql, reader => {
                    result.ParentMenuCaption = reader.GetString(0);
                }, p);
            }

            sql = "select name from psi_fid where id = @id";
            p = db.CreateDbParameters();
            p.AddWithValue("id", result.FId);
            db.Query(sql, reader => {
                result.FIdCaption = reader.GetString(0);
            }, p);

            if (result.FId != string.Empty) {
                result.FIdCaption += "(" + result.FId + ")";
            }

            result.Id = id;
            return result;
        }
    }
}